package com.example.myapplication.peripheral;

import android.graphics.Color;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.ScatterChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.ScatterData;
import com.github.mikephil.charting.data.ScatterDataSet;

import java.util.ArrayList;
import java.util.List;

public class PlotWave {
    private static final String TAG = "PlotWave";
    private static PlotWave INSTANCE;
    public synchronized static PlotWave getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new PlotWave();
        }
        return INSTANCE;
    }
    /**
     * 用于存储数据的列表
     */
    public List<Entry> ecgEntries = new ArrayList<>();
    public List<Entry> accXEntries = new ArrayList<>();
    public List<Entry> accYEntries = new ArrayList<>();
    public List<Entry> accZEntries = new ArrayList<>();
    public List<Entry> breathEntriesCH0 = new ArrayList<>();
    public List<Entry> breathEntriesCH1 = new ArrayList<>();
    public List<Entry> ppgEntriesRED = new ArrayList<>();
    public List<Entry> ppgEntriesIR = new ArrayList<>();
    /**
     * 数据index
     */
    public int ecgEntries_index = 0;
    public int accEntries_index = 0;
    public int breatheEntries_index = 0;
    public int ppgEntries_index = 0;
    /**
     * initChart
     * @param chart
     * @param label
     * @param color
     */
    public void initChart(LineChart chart, String label, int color) {
        // 禁用描述
        chart.getDescription().setEnabled(false);

        // 启用触摸手势
        chart.setTouchEnabled(true);

        // 启用缩放和拖动
        chart.setDragEnabled(true);
        chart.setScaleEnabled(true);
        chart.setPinchZoom(true);

        // 设置背景颜色
        chart.setBackgroundColor(Color.WHITE);

        // 配置X轴
        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f);
        xAxis.setDrawLabels(false); // 禁用X轴标签（索引）
        xAxis.setEnabled(true);//保留横线

        // 配置左侧Y轴
        YAxis leftAxis = chart.getAxisLeft();
        leftAxis.setDrawGridLines(true);
        leftAxis.setGranularity(0.1f);

        // 禁用右侧Y轴
        YAxis rightAxis = chart.getAxisRight();
        rightAxis.setEnabled(false);

        // 创建空数据
        LineData data = new LineData();
        chart.setData(data);

        // 刷新图表
        chart.invalidate();
    }

    /**
     * initMultiLineChart
     * @param chart
     * @param label
     * @param colors
     * @param labels
     */
    public void initMultiLineChart(LineChart chart, String label, int[] colors, String[] labels) {
        chart.getDescription().setEnabled(false);
        chart.setTouchEnabled(true);
        chart.setDragEnabled(true);
        chart.setScaleEnabled(true);
        chart.setPinchZoom(true);
        chart.setBackgroundColor(Color.WHITE);

        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f);
        xAxis.setDrawLabels(false); // 禁用X轴标签（索引）
        xAxis.setEnabled(true);//保留横线

        YAxis leftAxis = chart.getAxisLeft();
        leftAxis.setDrawGridLines(true);
        leftAxis.setGranularity(0.1f);

        YAxis rightAxis = chart.getAxisRight();
        rightAxis.setEnabled(false);

        // 创建多个数据集
        LineData lineData = new LineData();
        for (int i = 0; i < colors.length; i++) {
            LineDataSet dataSet = new LineDataSet(new ArrayList<Entry>(), labels[i]);
            dataSet.setColor(colors[i]);
            dataSet.setLineWidth(1.5f);
            dataSet.setDrawCircles(false);
            dataSet.setDrawValues(false);
            dataSet.setMode(LineDataSet.Mode.LINEAR);
            lineData.addDataSet(dataSet);
        }

        chart.setData(lineData);
        chart.invalidate();
    }
    /**
     * 更新绘图框
     * @param chart
     * @param entries
     * @param label
     * @param color
     */
    public void updateChart(LineChart chart, List<Entry> entries, String label, int color, int MAX_DATA, int UPDATE_DATA) {
        LineDataSet dataSet;

        if (chart.getData() != null && chart.getData().getDataSetCount() > 0) {
            dataSet = (LineDataSet) chart.getData().getDataSetByIndex(0);
            dataSet.setValues(entries);
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();
        } else {
            dataSet = new LineDataSet(entries, label);
            dataSet.setColor(color);
            dataSet.setLineWidth(1.5f);
            dataSet.setDrawCircles(false);
            dataSet.setDrawValues(false);
            dataSet.setMode(LineDataSet.Mode.LINEAR);

            LineData lineData = new LineData(dataSet);
            chart.setData(lineData);
        }

        setVisibleXRangeMaximum(chart, entries, MAX_DATA);
        chart.setVisibleXRangeMaximum(MAX_DATA);
        // 按批次更新滚动位置，实现“窗口批量滑动”
        if (!entries.isEmpty()) {
            int latestIndex = entries.size() - 1;
            int targetX = Math.max(0, latestIndex - MAX_DATA + UPDATE_DATA);
            chart.moveViewToX(targetX);
        }
        chart.invalidate();
    }

    public void updateChart1(LineChart chart, List<Entry> entries, String label, int color, int MAX_DATA, int UPDATE_DATA, long animateDuration) {
        LineDataSet dataSet;
        if (chart.getData() != null && chart.getData().getDataSetCount() > 0) {
            dataSet = (LineDataSet) chart.getData().getDataSetByIndex(0);
            dataSet.setValues(entries);
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();

        } else {
            dataSet = new LineDataSet(entries, label);
            dataSet.setColor(color);
            dataSet.setLineWidth(1.5f);
            dataSet.setDrawCircles(false);
            dataSet.setDrawValues(false);
            dataSet.setMode(LineDataSet.Mode.LINEAR);

            LineData lineData = new LineData(dataSet);
            chart.setData(lineData);
        }

        adjustYAxisRange(chart, entries, MAX_DATA);
        chart.setVisibleXRangeMaximum(MAX_DATA);

        if (!entries.isEmpty()) {
            chart.moveViewToX(entries.size() - 1);
        }
        chart.animateX((int) animateDuration); // 500ms animation duration
    }

    public void updateChart1(LineChart chart, List<Entry> entries, String label, int color, int MAX_DATA, int UPDATE_DATA, long animateDuration, int maxY, int minY) {
        LineDataSet dataSet;
        if (chart.getData() != null && chart.getData().getDataSetCount() > 0) {
            dataSet = (LineDataSet) chart.getData().getDataSetByIndex(0);
            dataSet.setValues(entries);
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();

        } else {
            dataSet = new LineDataSet(entries, label);
            dataSet.setColor(color);
            dataSet.setLineWidth(1.5f);
            dataSet.setDrawCircles(false);
            dataSet.setDrawValues(false);
            dataSet.setMode(LineDataSet.Mode.LINEAR);

            LineData lineData = new LineData(dataSet);
            chart.setData(lineData);
        }
        YAxis leftAxis = chart.getAxisLeft();
        leftAxis.setAxisMaximum(maxY);
        leftAxis.setAxisMinimum(minY);

        //adjustYAxisRange(chart, entries, MAX_DATA);
        chart.setVisibleXRangeMaximum(MAX_DATA);

        if (!entries.isEmpty()) {
            chart.moveViewToX(entries.size() - 1);
        }
        chart.animateX((int) animateDuration);
    }

//public void updateChart1(LineChart chart, List<Entry> entries, String label,
//                         int color, int MAX_DATA, int UPDATE_DATA,
//                         long animateDuration, int maxY, int minY) {
//    // 取消任何正在进行的动画
//
//
//    LineDataSet dataSet;
//    if (chart.getData() != null && chart.getData().getDataSetCount() > 0) {
//        dataSet = (LineDataSet) chart.getData().getDataSetByIndex(0);
//        dataSet.setValues(entries);
//        chart.getData().notifyDataChanged();
//        chart.notifyDataSetChanged();
//    } else {
//        dataSet = new LineDataSet(entries, label);
//        dataSet.setColor(color);
//        dataSet.setLineWidth(1.5f);
//        dataSet.setDrawCircles(false);
//        dataSet.setDrawValues(false);
//        dataSet.setMode(LineDataSet.Mode.LINEAR);
//
//        LineData lineData = new LineData(dataSet);
//        chart.setData(lineData);
//    }
//
//    YAxis leftAxis = chart.getAxisLeft();
//    leftAxis.setAxisMaximum(maxY);
//    leftAxis.setAxisMinimum(minY);
//
//    chart.setVisibleXRangeMaximum(MAX_DATA);
//
//    // 先移动视图到正确位置
//    if (!entries.isEmpty()) {
//        chart.moveViewToX(entries.size() - 1);
//    }
//
//    // 延迟一点时间再执行动画，确保视图移动完成
//    chart.postDelayed(() -> {
//        chart.animateX((int) animateDuration);
//    }, 50);
//}

    /**
     * 更新多参数绘图框
     * @param chart
     * @param entriesList
     * @param labels
     * @param colors
     */
    public void updateMultiLineChart(LineChart chart, List<Entry>[] entriesList, String[] labels, int[] colors,int MAX_DATA, int UPDATE_DATA) {
        LineData lineData = chart.getData();

        if (lineData == null || lineData.getDataSetCount() != entriesList.length) {
            // 如果数据不匹配，重新创建
            lineData = new LineData();
            for (int i = 0; i < entriesList.length; i++) {
                LineDataSet dataSet = new LineDataSet(entriesList[i], labels[i]);
                dataSet.setColor(colors[i]);
                dataSet.setLineWidth(1.5f);
                dataSet.setDrawCircles(false);
                dataSet.setDrawValues(false);
                dataSet.setMode(LineDataSet.Mode.LINEAR);
                lineData.addDataSet(dataSet);
            }
            chart.setData(lineData);
        } else {
            // 更新现有数据集
            for (int i = 0; i < entriesList.length; i++) {
                LineDataSet dataSet = (LineDataSet) lineData.getDataSetByIndex(i);
                dataSet.setValues(entriesList[i]);
            }
            lineData.notifyDataChanged();
            chart.notifyDataSetChanged();
        }

        setVisibleXRangeMaximum(chart, entriesList, MAX_DATA);
        chart.setVisibleXRangeMaximum(MAX_DATA);
        if (!entriesList[0].isEmpty()) {
            int latestIndex = entriesList[0].size() - 1;
            int targetX = Math.max(0, latestIndex - MAX_DATA + UPDATE_DATA);
            chart.moveViewToX(targetX);
        }
        chart.invalidate();
    }

    public void setVisibleXRangeMaximum(LineChart chart, List<Entry> entries, int MAX_DATA){
        // 计算当前可视窗口范围内的最大/最小值
        int size = entries.size();
        if (size > 0) {
            int start = Math.max(0, size - MAX_DATA);
            int end = size;

            float minY = Float.MAX_VALUE;
            float maxY = Float.MIN_VALUE;

            for (int i = start; i < end; i++) {
                float y = entries.get(i).getY();
                if (y < minY) minY = y;
                if (y > maxY) maxY = y;
            }

            // 增加上下边距（比如5%）
            float padding = (maxY - minY) * 0.05f;
            if (padding == 0) padding = 1f; // 避免上下限一致时出现异常

            YAxis leftAxis = chart.getAxisLeft();
            leftAxis.setAxisMinimum(minY - padding);
            leftAxis.setAxisMaximum(maxY + padding);
        }
    }
    public void adjustYAxisRange(LineChart chart, List<Entry> entries, int MAX_DATA){
        // 计算当前可视窗口范围内的最大/最小值
        int size = entries.size();
        if (size > 0) {
            int start = Math.max(0, size - MAX_DATA);
            int end = size;

            float minY = Float.MAX_VALUE;
            float maxY = Float.MIN_VALUE;

            for (int i = start; i < end; i++) {
                float y = entries.get(i).getY();
                if (y < minY) minY = y;
                if (y > maxY) maxY = y;
            }

            // 增加上下边距（比如5%）
            float padding = (maxY - minY) * 0.15f;
            if (padding == 0) padding = 1f; // 避免上下限一致时出现异常

            YAxis leftAxis = chart.getAxisLeft();
            leftAxis.setAxisMinimum(minY - padding);
            leftAxis.setAxisMaximum(maxY + padding);
            //Log.d(TAG, "setVisibleXRangeMaximum: minY=" + (minY - padding) + ", maxY=" + (maxY + padding));
        }
    }

    public void setVisibleXRangeMaximum(LineChart chart, List<Entry>[] entriesList, int MAX_DATA){
        float MinRange = Float.MAX_VALUE;
        float MaxRange = Float.MIN_VALUE;;
        for (List<Entry> entries : entriesList) {
            // 计算当前可视窗口范围内的最大/最小值
            int size = entries.size();
            if (size > 0) {
                int start = Math.max(0, size - MAX_DATA);
                int end = size;

                float minY = Float.MAX_VALUE;
                float maxY = Float.MIN_VALUE;

                for (int i = start; i < end; i++) {
                    float y = entries.get(i).getY();
                    if (y < minY) minY = y;
                    if (y > maxY) maxY = y;
                }
                if(minY < MinRange)
                    MinRange = minY;
                if(maxY > MaxRange)
                    MaxRange = maxY;
            }
        }
        // 增加上下边距（比如5%）
        float padding = (MaxRange - MinRange) * 0.05f;
        if (padding == 0) padding = 1f; // 避免上下限一致时出现异常
        YAxis leftAxis = chart.getAxisLeft();
        leftAxis.setAxisMinimum(MinRange - padding);
        leftAxis.setAxisMaximum(MaxRange + padding);
    }

    public void initChart(ScatterChart chart, String label, int color, float yMin, float yMax) {
        // 禁用描述
        chart.getDescription().setEnabled(false);

        // 启用触摸手势
        chart.setTouchEnabled(true);

        // 启用缩放和拖动
        chart.setDragEnabled(true);
        chart.setScaleEnabled(true);
        chart.setPinchZoom(true);

        // 设置背景颜色
        chart.setBackgroundColor(Color.WHITE);

        // 配置X轴
        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f);
        xAxis.setDrawLabels(false); // 禁用X轴标签（索引）
        xAxis.setEnabled(true); // 保留横线

        // 配置左侧Y轴
        YAxis leftAxis = chart.getAxisLeft();
        leftAxis.setDrawGridLines(true);
        leftAxis.setGranularity(0.1f);
        leftAxis.setAxisMinimum(yMin); // 设置Y轴最小值
        leftAxis.setAxisMaximum(yMax); // 设置Y轴最大值
        // 禁用右侧Y轴
        YAxis rightAxis = chart.getAxisRight();
        rightAxis.setEnabled(false);

        // 创建空数据
        ScatterData data = new ScatterData();
        chart.setData(data);

        // 刷新图表
        chart.invalidate();
    }

    public void updateChart(ScatterChart chart, List<Entry> entries, String label, int color, int MAX_DATA, int UPDATE_DATA) {
        ScatterDataSet dataSet;

        if (chart.getData() != null && chart.getData().getDataSetCount() > 0) {
            dataSet = (ScatterDataSet) chart.getData().getDataSetByIndex(0);
            dataSet.setValues(entries);
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();
        } else {
            dataSet = new ScatterDataSet(entries, label);
            dataSet.setColor(color); // 设置数据点颜色
            dataSet.setScatterShapeSize(10f); // 设置数据点大小
            dataSet.setScatterShape(ScatterChart.ScatterShape.CIRCLE); // 设置形状（圆形）
            dataSet.setDrawValues(false); // 不显示数值标签

            ScatterData scatterData = new ScatterData(dataSet);
            chart.setData(scatterData);
        }

        // 设置可见范围
        chart.setVisibleXRangeMaximum(MAX_DATA);
        if (!entries.isEmpty()) {
            int latestIndex = entries.size() - 1;
            int targetX = Math.max(0, latestIndex - MAX_DATA + UPDATE_DATA);
            chart.moveViewToX(targetX);
        }
        chart.invalidate();
    }
}
